import axios from 'axios';

// axios.defaults.timeout=5000;//设置超时时间
// axios.defaults.withCredentials=true;//允许跨域
// //Content-Type 响应头
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
// axios.defaults.headers({
//   'jzbooks-api': 'eyJhbGciOiJIUzI1NiJ9.eyJ0eXBlIjoxLCJleHAiOjE2MjE5OTExNjksInVzZXJJZCI6MSwianRpIjoiYWNjOGM2MGItMjkyYi00NDNjLTk1YzYtN2UwZDg3NGJmZDk0In0.btBBpAjMhfopR1XWNnRTEjsyY6jgzOHqGXeQQZ7jLC8',
//   'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
// })


//请求URL
// axios.defaults.baseURL="http://localhost:7999";

const api = axios.create({
  baseURL: "http://localhost:7999",
  timeout: 5000,
  withCredentials: true,
  headers: {
    'jzbooks-api': 'eyJhbGciOiJIUzI1NiJ9.eyJ0eXBlIjoxLCJleHAiOjE2MjE5OTExNjksInVzZXJJZCI6MSwianRpIjoiYWNjOGM2MGItMjkyYi00NDNjLTk1YzYtN2UwZDg3NGJmZDk0In0.btBBpAjMhfopR1XWNnRTEjsyY6jgzOHqGXeQQZ7jLC8',
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    'whetherSwagger': 'yes'
  }
})



//响应拦截器
api.interceptors.response.use(
  response  => {
    // console.log('response111:   ',response.data);
    if (response.data.code === 1 ){
      return Promise.resolve(response)
      // console.log('response:   ',response.data.data);
    }else {
      return Promise.reject(response)
    }
  },
  error => {
    if (error.response.data.code){
      switch (error.response.data.code) {
        case 401: //未登入
          router.replace({
            path: '/',
            query: {
              redirect: router.currentRoute.fullPath
            }
          });
          break;
        case 404:
          break;
      }
    }
  }
  );


/**
 *  封装get方法
 */
export function get(url,params={}) {
  return new Promise((resolve,reject) => {
    api.get(url,{params:params})
      .then(response => {
        // console.log("response:  "+response.data);
        resolve(response.data);
      })
      .then(err => {
        reject(err)
      })
  })
}

/**
 *  封装post方法
 */
export function post(url,data={}) {
  return new Promise((resolve,reject) => {
    api.post(url,data)
      .then(response => {
        resolve(response.data);
      },err => {
        reject(err)
        }
      )
  })
}
